package adv.i31.robot;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;


public class RobotConnectionIp4 implements RobotConnection {

	private Socket mSocket;
	private BufferedWriter mWriter;
	private BufferedReader mReader;

	public RobotConnectionIp4() {
	}

	public void connect(InetSocketAddress address) throws IOException {
		mSocket = new Socket();
		mSocket.connect(new InetSocketAddress(address.getHostName(), address.getPort()));
		mWriter = new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream()));
		mReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
	}

	public void disconnect() throws IOException {
		if (mSocket != null) {
			// mSocket.shutdownOutput();
			mSocket.close();
		}
	}

	@Override
	public void sendString(String s) throws IOException {
		mWriter.write(s);
		mWriter.flush();
	}

	@Override
	public String receiveString() throws IOException {
		return mReader.readLine();
	}

	@Override
	public OutputStream getOutputStream() throws IOException {
		return mSocket.getOutputStream();
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return mSocket.getInputStream();
	}

}